package cn.zhagzheguo.xk.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.zhagzheguo.xk.config.FileConfig;
import cn.zhagzheguo.xk.dao.CourseFileDao;
import cn.zhagzheguo.xk.model.CourseFile;
import cn.zhagzheguo.xk.status.CommonStatus;
import cn.zhagzheguo.xk.util.DateFormatUtil;
import cn.zhagzheguo.xk.util.NumberFormatUtil;
import cn.zhagzheguo.xk.util.UuidUtil;

@Controller
@RequestMapping("/file")
public class CourseFileController {

	@Autowired
	private CourseFileDao cfDao;

	@RequestMapping("/upload")
	public String showUploadPage() {
		System.out.println("uploading...");
		return "/uploadPage.jsp";
	}

	@RequestMapping("/upload1")
	public String showUploadPage1() {
		System.out.println("uploading...");
		return "/uploadSuccess.html";
	}

	@RequestMapping("/course")
	@ResponseBody
	public List<CourseFile> courseFiles(@RequestParam("course_id") int course_id) {
		List<CourseFile> list = cfDao.getAllByCourseId(course_id);
		System.out.println("/file/course list=" + list.toString());
		return list;
	}

	// , produces = { "application/*;charset=UTF-8" }
	@RequestMapping(value = { "/download/images/*", "/download/headIcon/*" })
	public void download(HttpServletRequest request, HttpServletResponse response) {

		String sourceName = request.getServletPath();
		// System.out.println("sourceName=" + sourceName);//
		// /file/download/65456.doc

		String filePath = sourceName.substring(sourceName.indexOf("/file/download/") + 15);

		/*
		 * try { filePath = URLDecoder.decode(new
		 * String(filePath.getBytes("ISO-8859-1")), "UTF-8"); } catch
		 * (UnsupportedEncodingException e1) { e1.printStackTrace(); }
		 */

		// file/download/images/pic1.jpg
		String absoluteImagePath = FileConfig.FILE_ROOT + filePath;
		System.out.println("download " + absoluteImagePath);
		FileInputStream fis = null;
		OutputStream out = null;

		// 强制改文件名
		// response.setHeader("Content-Disposition", "attachment;filename=" +
		// fileName);

		try {
			out = response.getOutputStream();

			File file = new File(absoluteImagePath);
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int i = 0;

			while ((i = fis.read(b)) > 0) {
				out.write(b, 0, i);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 专属文件下载方法
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = { "/download/files/*" })
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) {

		String sourceName = request.getServletPath();
		// System.out.println("sourceName=" + sourceName);//
		// /file/download/65456.doc

		String filePath = sourceName.substring(sourceName.indexOf("/file/download/") + 15);

		String absoluteImagePath = FileConfig.FILE_ROOT + filePath;
		System.out.println("download " + absoluteImagePath);
		FileInputStream fis = null;
		OutputStream out = null;

		try {
			/* 文件传输 */
			out = response.getOutputStream();
			File file = new File(absoluteImagePath);

			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
			response.addHeader("Content-Length", "" + file.length());
			response.setContentType("application/octet-stream;charset=UTF-8");

			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int i = 0;

			while ((i = fis.read(b)) > 0) {
				out.write(b, 0, i);
			}
			out.flush();
			out.close();

			/* 文件传输完成，进行业务操作 */
			// 通过sourceName进行查找并使下载量加1
			System.out.println("Downloading file... sourceName=" + sourceName);
			String fileName = sourceName.substring(sourceName.lastIndexOf("/") + 1);
			cfDao.addDownloadCount(fileName);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("/doUpload")
	public String doUploadFile(@RequestParam("file") MultipartFile file, CourseFile cf) {

		if (cf.getStu_id() == 0 || cf.getCourse_id() == 0) {
			return "/static/redirect:uploadFail.html";
		}

		if (!file.isEmpty()) {
			try {
				if (cf != null) {
					System.out.println("cf:" + cf.toString());
					// 得到文件名。
					String fileName = cf.getName();
					if ("".equals(fileName) || fileName == null) {
						fileName = file.getOriginalFilename();
					}
					// 得到后缀
					String suffix = file.getOriginalFilename().substring(
							file.getOriginalFilename().lastIndexOf(".") + 1);

					fileName += "." + suffix;
					String trueFileName = UuidUtil.getUuid() + "." + suffix;
					// 保存到本地
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File(FileConfig.FILE_ROOT + "files/"
							+ trueFileName));
					// 添加其他信息
					cf.setDate(DateFormatUtil.format(new Date()));
					cf.setDownloadCount(0);
					cf.setName(fileName);
					cf.setPath("file/download/files/" + trueFileName);

					// 计算size
					if (file.getSize() / 1024.0 / 1024.0 <= 1) {
						cf.setSize(NumberFormatUtil.format(file.getSize() / 1024.0 + "", 2) + " KB");
					} else {
						cf.setSize(NumberFormatUtil.format(file.getSize() / 1024.0 / 1024.0 + "", 2) + " M");
					}

					int result = cfDao.insert(cf);
					if (result == CommonStatus.SUCCESS) {
						return "redirect:/static/uploadSuccess.html";
					} else {
						File ff = new File(FileConfig.FILE_ROOT + "files/" + trueFileName);
						if (ff.exists()) {
							ff.delete();
							ff = null;
						}
						return "redirect:/static/uploadFail.html";
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "/static/redirect:uploadFail.html";
	}

	public void setCfDao(CourseFileDao cfDao) {
		this.cfDao = cfDao;
	}
}
